package vn.gq.tym.storytemplate;

import java.util.ArrayList;

import net.simonvt.numberpicker.NumberPicker;
import vn.gq.tym.fragment.WebviewFragment;
import vn.gq.tym.widget.PopupWindow;
import vn.gq.udv.db.DbAdapter;
import vn.gq.udv.db.items.ChapterDetail;
import vn.gq.udv.db.items.ChapterItem;
import vn.gq.udv.db.items.ISetChapterItem;
import vn.gq.udv.utils.AdmobAdsHandler;
import vn.gq.udv.utils.Bookmark;
import vn.gq.udv.utils.ButtonHelper;
import vn.gq.udv.utils.DialogUtils;
import vn.gq.udv.utils.MyViewPager;
import vn.gq.udv.utils.Settings;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.ads.AdView;

public class StoryReaderActivity extends SherlockFragmentActivity implements OnPageChangeListener, OnTouchListener {

	private ArrayList<ChapterItem> mData;
	private int mCurrentPosition = 0;
	private MyViewPager mViewPager;
	private ReaderViewPagerAdapter mAdapter;
	private ReaderButtonHandler mButtonHandler;
	private Handler mHandler = new Handler();
	private GestureDetector gestureDetector;
	private LinearLayout mainLayout;
	private PopupWindow mPopupWindow;
	private AdmobAdsHandler mAdsHandler;
	private int mCurrentScrollYPos = 0;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		gestureDetector = new GestureDetector(this, new SimpleGestureListener());
		setContentView(R.layout.activity_reader);
		Bundle args = getIntent().getExtras();
		if (args != null) {
			mData = args.getParcelableArrayList("DATA");
			mCurrentPosition = args.getInt("POSITION");
		}
		mViewPager = (MyViewPager) findViewById(R.id.viewpager);
		mViewPager.setPagingEnable(false);
		mAdapter = new ReaderViewPagerAdapter(getSupportFragmentManager());
		mViewPager.setAdapter(mAdapter);
		mViewPager.setOffscreenPageLimit(3);
		mViewPager.setCurrentItem(mCurrentPosition);
		mViewPager.setOnPageChangeListener(this);
		mButtonHandler = new ReaderButtonHandler((ImageView) findViewById(R.id.btnPrev), (ImageView) findViewById(R.id.btnNext));
		mButtonHandler.showButton(mCurrentPosition);
		initPopup();
		mAdsHandler = new AdmobAdsHandler((AdView) findViewById(R.id.adView));
		TextView tv = (TextView) findViewById(R.id.notification);
		tv.setEnabled(true);
		tv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new ButtonHelper(StoryReaderActivity.this).showMoreApp();
			}
		});
	}
	
	public void initPopup() {
		mainLayout = (LinearLayout) findViewById(R.id.reader_container);
		final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mPopupWindow = new PopupWindow(this);
		ViewGroup popupView = (ViewGroup) inflater.inflate(R.layout.popup, null, false);
		mPopupWindow.setContentView(popupView);
		final Settings setting = new Settings(this);
		Button changeFontBtn = (Button) popupView.findViewById(R.id.btnChangeFont);
		changeFontBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(StoryReaderActivity.this);
				View pickerView = inflater.inflate(R.layout.number_picker_layout, null, false);
				final NumberPicker numberPicker = (NumberPicker) pickerView.findViewById(R.id.numberPicker);
				numberPicker.setMaxValue(30);
				numberPicker.setMinValue(10);
				numberPicker.setValue(setting.getFontSize(16));
				builder.setInverseBackgroundForced(true)
				.setView(pickerView)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						int size = numberPicker.getValue();
						setting.setFontSize(size);
						mViewPager.getAdapter().notifyDataSetChanged();
					}
				})
				.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				})
				
				.create().show();
			}
		});
		
		((Button) popupView.findViewById(R.id.btnDayMode)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setting.setNightMode(false);
				mViewPager.getAdapter().notifyDataSetChanged();
			}
		});
		
		((Button) popupView.findViewById(R.id.btnNightMode)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setting.setNightMode(true);
				mViewPager.getAdapter().notifyDataSetChanged();
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mAdsHandler.loadAds();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mAdsHandler.onDestroy();
	}

	public static void startActivity(Context context, ArrayList<ChapterItem> data, int position) {
		Intent intent = new Intent(context, StoryReaderActivity.class);
		intent.putParcelableArrayListExtra("DATA", data);
		intent.putExtra("POSITION", position);
		context.startActivity(intent);
	}
	
	public class ReaderViewPagerAdapter extends FragmentStatePagerAdapter {

		public ReaderViewPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			ChapterItem chapterItem = mData.get(position);
			chapterItem.setPosition(position);
			ChapterDetail detail = new DbAdapter(getApplicationContext()).getChapterDetailById(chapterItem.getId());
			Fragment fragment = WebviewFragment.newInstance(String.format("files/%s", detail.getDetail()), chapterItem.getScrollY());
			return fragment;
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}
	}

	@Override
	public void onPageScrollStateChanged(int position) {
		
	}

	@Override
	public void onPageScrolled(int position, float arg1, int arg2) {
		
	}

	@Override
	public void onPageSelected(int position) {
		mButtonHandler.showButton(position);
		mAdsHandler.loadAds();
	}
	
	public enum TypeDisplayButton {
		ONLY_PREV_BTN, ONLY_NEXT_BTN, BOTH
	}
	
	public class ReaderButtonHandler implements OnClickListener {
		
		private ImageView prevBtn, nextBtn;
		
		public ReaderButtonHandler(ImageView prevBtn, ImageView nexBtn) {
			this.prevBtn = prevBtn;
			this.nextBtn = nexBtn;
			this.nextBtn.setOnClickListener(this);
			this.prevBtn.setOnClickListener(this);
		}
		
		public ReaderButtonHandler(ViewGroup root, int prevBtnId, int nextBtnId) {
			if (root != null) {
				prevBtn = (ImageView) root.findViewById(prevBtnId);
				nextBtn = (ImageView) root.findViewById(nextBtnId);
			}
		}
		
		public void showButton(int position) {
			if (position >= (mData.size() - 1)) {
				mButtonHandler.showButton(TypeDisplayButton.ONLY_PREV_BTN);
			} else if(position > 0) {
				mButtonHandler.showButton(TypeDisplayButton.BOTH);
			} else {
				mButtonHandler.showButton(TypeDisplayButton.ONLY_NEXT_BTN);
			}
		}
		
		private Runnable hideButtonRun = new Runnable() {
			
			@Override
			public void run() {
				prevBtn.setVisibility(View.GONE);
				nextBtn.setVisibility(View.GONE);
			}
		};
		
		public void showButton(TypeDisplayButton type) {
			showOrHideButton(type, true);
		}
		
		public void showOrHideButton(TypeDisplayButton type, boolean isShow) {
			switch(type) {
				case BOTH:
					prevBtn.setVisibility(isShow ? View.VISIBLE : View.GONE);
					nextBtn.setVisibility(isShow ? View.VISIBLE : View.GONE);
					break;
				case ONLY_NEXT_BTN:
					nextBtn.setVisibility(isShow ? View.VISIBLE : View.GONE);
					prevBtn.setVisibility(isShow ? View.GONE : View.VISIBLE);
					break;
				case ONLY_PREV_BTN:
					prevBtn.setVisibility(isShow ? View.VISIBLE : View.GONE); 
					nextBtn.setVisibility(isShow ? View.GONE : View.VISIBLE);
					break;
				}
			
			if (isShow) {
				mHandler.removeCallbacks(hideButtonRun);
				mHandler.postDelayed(hideButtonRun, 2500);
			}
		}

		@Override
		public void onClick(View v) {
			int pos = mViewPager.getCurrentItem();
			if (v.equals(nextBtn)) {
				if (pos < mData.size() - 1) {
					mViewPager.setCurrentItem(pos+1, true);
				}
			} else if (v.equals(prevBtn)) {
				if (pos > 0) {
					mViewPager.setCurrentItem(pos-1, true);
				}
			}
		}
	}

	
	private WebView visibleWebview;
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		visibleWebview = (WebView) v;
		return gestureDetector.onTouchEvent(event);
	}
	
	
	public class SimpleGestureListener extends GestureDetector.SimpleOnGestureListener {

		@Override
		public boolean onDown(MotionEvent e) {
			mCurrentScrollYPos = visibleWebview.getScrollY();
			mButtonHandler.showButton(mViewPager.getCurrentItem());
			return super.onDown(e);
		}

		@Override
		public boolean onDoubleTap(MotionEvent e) {
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			} else {
				mPopupWindow.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10);
			}
			return true;
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			return true;
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			return true;
		}
	}
	
	public void onBack() {
		super.onBackPressed();
	}

	@Override
	public void onBackPressed() {
		
		ChapterItem chapterItem = mData.get(mViewPager.getCurrentItem());
		chapterItem.setScrollYPos(mCurrentScrollYPos);
		
		new Bookmark(StoryReaderActivity.this).setChapterBookmark(chapterItem);
		new DialogUtils(StoryReaderActivity.this).showConfirm("Đánh dấu chương đang đọc ?", new DialogUtils.OnDialogConfirmListener() {
			
			@Override
			public void onOk() {
				onBack();
			}

			@Override
			public void onCancel() {
				onBack();
			}
		});
		
	}

	
}
